package com.ithema.notebook.processor;

import com.intellij.ide.fileTemplates.impl.UrlUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Package: com.ithema.notebook.processor
 * Description：
 * MD 渲染
 * @author: huangjian
 * Date:  2020/10/18 17:18
 * Modified By:
 */
public class MDFreemarkerProcessor extends AbstractFreemarkerProcessor {
    @Override
    protected Object getModel(SourceNoteData sourceNoteData) {
        Map<String,Object> model=new HashMap<>();
        model.put("topic",sourceNoteData.topic());
        model.put("noteList",sourceNoteData.getContent());
        return model;
    }

    @Override
    protected Template getTemplate() throws IOException {
        Configuration configuration=new Configuration(Configuration.VERSION_2_3_28);
        String context = UrlUtil.loadText(MDFreemarkerProcessor.class.getResource("/template/md.ftl"));
        StringTemplateLoader stringTemplateLoader=new StringTemplateLoader();
        stringTemplateLoader.putTemplate("MDTemplate",context);
        configuration.setTemplateLoader(stringTemplateLoader);
        return configuration.getTemplate("MDTemplate");
    }

    @Override
    protected Writer getWriter(SourceNoteData sourceNoteData) throws Exception {
        String fileName = sourceNoteData.getFileName();
        return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), "utf-8"));
    }
}
